package org.lee.system.service.impl;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.solon.service.impl.ServiceImpl;
import org.lee.common.constant.CacheConstants;
import org.lee.common.core.service.redis.RedisService;
import org.lee.system.mapper.SysConfigMapper;
import org.lee.system.model.SysConfig;
import org.lee.system.service.SysConfigService;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.core.bean.LifecycleBean;

import java.util.Collection;
import java.util.List;

@Component
public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig> implements SysConfigService, LifecycleBean {

    @Inject
    private RedisService redisService;

    @Override
    public String selectConfigByKey(String key) {
        String configValue = redisService.getCacheObject(getCacheKey(key));
        if (CharSequenceUtil.isNotEmpty(configValue)) {
            return configValue;
        }
        SysConfig config = this.getOne(Wrappers.<SysConfig>lambdaQuery().eq(SysConfig::getConfigKey, key));
        if (ObjectUtil.isNull(config)) {
            return null;
        }
        return config.getConfigValue();
    }

    @Override
    public void start() {
        loadingConfigCache();
    }

    @Override
    public void stop() {
        clearConfigCache();
    }

    @Override
    public void loadingConfigCache() {
        List<SysConfig> configList = this.list();
        for (SysConfig config : configList) {
            redisService.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue());
        }
    }

    /**
     * 清空参数缓存数据
     */
    @Override
    public void clearConfigCache() {
        Collection<String> keys = redisService.keys(CacheConstants.SYS_CONFIG_KEY + "*");
        redisService.deleteObject(keys);
    }

    /**
     * 重置参数缓存数据
     */
    @Override
    public void resetConfigCache() {
        clearConfigCache();
        loadingConfigCache();
    }

    /**
     * 设置cache key
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    private String getCacheKey(String configKey) {
        return CacheConstants.SYS_CONFIG_KEY + configKey;
    }
}
